<?php

class Users_UserController extends Zend_Controller_Action {

	public function init() {
		if($this->_request->isXmlHttpRequest()) {
			// Отключаем авторендеринг шаблонов
			$this->_helper->viewRenderer->setNoRender();
			// Отключаем шаблоны
			$this->_helper->layout()->disableLayout();
		}
	}
	
	public function indexAction() {
		if($this->_request->isXmlHttpRequest()) {
			$users = Doctrine_Core::getTable('Users_Model_Users')->findAll();
			
			$users_array = array();
			
			foreach ($users as $key=>$user) {
				$users_array[$key]['id'] = $user->id;
				$users_array[$key]['username'] = $user->username;
				$users_array[$key]['role'] = $user->role;
				$users_array[$key]['email'] = $user->email;
				$users_array[$key]['delete'] = $user->delete;
				$users_array[$key]['last_enter'] = $user->last_enter;
				$users_array[$key]['date_created'] = $user->date_created;
				$users_array[$key]['last_ip'] = $user->last_ip;
			}
			
			$response_array = array(
				'users' => $users_array,
				'total' => $users->count(),
				'success' => true
			);
			
			$response = $this->getResponse();
			$response->appendBody(Zend_Json::encode($response_array))->setHeader('content-type', 'text/plain', true);
		}
	}
	
	public function createAction() {
		if($this->_request->isXmlHttpRequest()) {
			$user = new Users_Model_Users();
		
			$user->username = $this->_request->getParam('username');
			$user->email = $this->_request->getParam('email');
			$user->password = md5($this->_request->getParam('password'));
			$user->role = $this->_request->getParam('role');
			$user->date_created = time();
			$user->save();
			
			$array_response = array(
				'success' => true,
				'msg' => 'User added successfully!'
			);
			
			$response = $this->getResponse();
			$response->appendBody(Zend_Json::encode($array_response))->setHeader('content-type', 'text/plain', true);
		} else {
			$this->_redirect($this->view->url(array(),'users_user_index'));
		}
	}
	
	public function deleteAction() {
		if($this->_request->isXmlHttpRequest()) {
			$id = $this->_request->getParam('id');
			
			$user = Doctrine_Core::getTable('Users_Model_Users')->find($id);
			
			if($user) {
				$user->delete();
			}
			
			$response = $this->getResponse();
			$response->appendBody('User deleted successfully!')->setHeader('content-type', 'text/plain', true);
		} else {
			$this->_redirect($this->view->url(array(),'users_user_index'));
		}
	}
	
	public function updateAction() {
		if($this->_request->isXmlHttpRequest()) {
			$id = $this->_request->getParam('id');
			
			$user = Doctrine_Core::getTable('Users_Model_Users')->find($id);
			$user->username = $this->_request->getParam('username');
			$user->email = $this->_request->getParam('email');
			if($password = $this->_request->getParam('password', null)) {
				$user->password = md5($password);
			}
			$user->role = $this->_request->getParam('role');
			
			$user->save();
			
			$array_response = array(
				'success' => true,
				'msg' => 'User updated successfully!'
			);
			
			$response = $this->getResponse();
			$response->appendBody(Zend_Json::encode($array_response))->setHeader('content-type', 'text/plain', true);
		} else {
			$this->_redirect($this->view->url(array(),'users_user_index'));
		}
	}
	
	public function registerAction() {
		$form = new Users_Form_Register();
		$form->setAction($this->view->url(array(),'users_user_register'));
		if($this->_request->isPost() && $form->isValid($this->_request->getPost())) {
			$values = $form->getValues();
			
			$user = new Users_Model_Users();
			$user->date_created = time();
			$user->username = $values['username'];
			$user->password = md5($values['password']);
			$user->email = $values['email'];
			$user->role = 'guest';
			$user->save();
			
			return $this->_redirect($this->view->url(array(),'default_index_index'));
		}
		$this->view->form = $form;
	}
	
	/**
	* Напоминание пароля
	*/
	public function rememberAction() {
		$form = new Users_Form_Remember();
		$form->setAction($this->view->url(array(),'users_user_remember'));
		
		if($this->_request->isPost() && $form->isValid($this->_request->getPost())) {
			$values = $form->getValues();
			
			$user = Doctrine_Core::getTable('Users_Model_Users')->findOneByEmail($values['email']);
			if($user) {
				//генерируем код активации
				$chars = 'abdefhiknrstyzABDEFGHKNQRSTYZ23456789';
				$code = '';
				for($i = 0; $i < 32; $i++) {
					$code .= substr($chars, rand(1, strlen($chars)) - 1, 1);
				}
				
				//записываем код активации
				$user->code_activ = $code;
				$user->save();
				
				//оправляем письмо
				$settings = Doctrine_Core::getTable('Default_Model_Settings')->find(1);
				$msg = str_replace('%username%',$user->username,$settings->template_remember);
				$msg = str_replace('%sitename%',$this->view->SITENAME,$msg);
				
				$url = $this->view->STATIC_SERVER . $this->view->url(array('code' => $code),'users_user_activate');
				
				$msg = str_replace('%url%',$url,$msg);
				
				$mail = new Zend_Mail('KOI8-R');
					
				$mail->setBodyText(htmlspecialchars(iconv('utf-8', 'KOI8-R', $msg)));
					
				$mail->setSubject('=?KOI8-R?B?'.base64_encode(iconv('utf-8', 'KOI8-R', $this->view->SITENAME . ': Remember password')).'?=');
				
				$mail->addTo($user->email);
				$mail->send();
				
				$this->_helper
					->getHelper('FlashMessenger')
					->addMessage($this->view->translate('Done! Go to your email to continue'));
			} else {
				$this->_helper
					->getHelper('FlashMessenger')
					->addMessage($this->view->translate('User with this email does not exist'));
			}
			
			return $this->_redirect($this->view->url(array(),'users_user_remember'));
		}
		
		$this->view->form = $form;
	}
	
	/**
	* Вход по коду активации
	*/
	public function activateAction() {
		$code = $this->_request->getParam('code',null);
		$done = $this->_request->getParam('done',null);
		if($code && !$done) {
			$user = Doctrine_Core::getTable('Users_Model_Users')->findOneByCode_activ($code);
			
			if($user) {
				//авторизуем
				$auth = Zend_Auth::getInstance();
				
				$modelName = 'Users_Model_Users';
				
				$authAdapter = new ZendX_Doctrine_Auth_Adapter(Doctrine_Core::getConnectionByTableName($modelName),
									($modelName . ' u'),
									'u.username',
									'u.code_activ',
									'u.delete = "no"');
				$authAdapter->setIdentity($user->username)
							->setCredential($code);
				
				$result = $auth->authenticate($authAdapter);
				
				if ($result->isValid()) {
					$storage = new Zend_Auth_Storage_Session();
					$storage->write($authAdapter->getResultRowObject());
					
					$user->code_activ = '';
					$user->save();
					
					$this->_helper
							->getHelper('FlashMessenger')
							->addMessage($this->view->translate('You have successfully logged in! Edit information you can in your profile.'));
					return $this->_redirect($this->view->url(array('code' => $code, 'done' => 'done'), 'users_user_activate'));
				} else {
					$user->code_activ = '';
					$user->save();
					
					$this->_helper
							->getHelper('FlashMessenger')
							->addMessage($this->view->translate('User not found by active code in the system.'));

					return $this->_redirect($this->view->url(array('code' => $code, 'done' => 'done'), 'users_user_activate'));
				}
			} else {
				$this->_helper
					->getHelper('FlashMessenger')
					->addMessage($this->view->translate('User not found in the system.'));
				return $this->_redirect($this->view->url(array('code' => $code, 'done' => 'done'), 'users_user_activate'));
			}
		} elseif(!$done && !$code) {
			return $this->_redirect($this->view->url(array(), 'default_index_index'));
		}
		
	}
}